package com.devilwwj.http.callback;

import android.util.JsonReader;

import com.devilwwj.http.core.AbstractDataCallback;
import com.devilwwj.http.entities.IEntity;
import com.devilwwj.http.exception.HttpException;
import com.devilwwj.http.utils.LogUtils;

import java.io.FileReader;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

/**
 * Created by devilwwj on 15/7/25.
 */
public abstract class JSONReaderCallback<T extends IEntity> extends AbstractDataCallback<T> {
    @Override
    public T bindData(String path) throws HttpException {
        try {
            LogUtils.e("wwj", "JsonReaderCallback binddata:" + path);

            Type type = ((ParameterizedType)getClass().getGenericSuperclass()).getActualTypeArguments()[0];
            T t = ((Class<T> )type).newInstance();

            FileReader in = new FileReader(path);
            JsonReader reader = new JsonReader(in);
            String node;
            reader.beginObject();
            while(reader.hasNext()) {
                node = reader.nextName();
                if ("data".equalsIgnoreCase(node)) {
                    t.readFromJson(reader);
                } else {
                    reader.skipValue();
                }
            }
            reader.endObject();
            return t;
        } catch (Exception e) {
          throw new HttpException(HttpException.ErrorType.JSON,e.getMessage());
        }
    }
}
